// import {
// 	host,
// 	develop
// } from '@/config/config.js'
import {
	host,
	develop,config
} from '@/utils/config.js'
import {
	weatherKey
} from '@/utils/constants.js'
// 请求白名单
const requestWhiteList = [
	'https://v.api.aa1.cn/api/api-vs/index.php',//退出登录
	
]
// /获取token中
let tokenLoading = false
// 获取token中请求的接口缓存起来
let requestQueue = []
// 请求数
let resqNum = 0
// 验证token是否失效
var expired = false;
let requestRecord = {

}
let httpConfig = {
	header: {
		// 'Content-Type': "application/json",
		'Content-Type': "application/x-www-form-urlencoded;application/json",
		// 'Content-Type': "application/x-www-form-urlencoded;",
		'token':'',
	},
	postHeader: {
		'Content-Type': "application/json",
		// 'Content-Type': "application/x-www-form-urlencoded",
		'token':'',
	},
	method: 'POST',
	showLoading: true, // 是否显示请求中的loading
	loadingText: '请求中...',
	loadingTime: 800, // 在此时间内，请求还没回来的话，就显示加载中动画，单位ms
	timer: null, // 定时器
	loadingMask: false, // 展示loading的时候，是否给一个透明的蒙层，防止触摸穿透
	stopRepeat: false, // 是否阻止重复请求
	timeout: 15000, // 请求超时时间
	errorOutput: true, // 请求失败输出信息
	
	// cookie: uni.getStorageSync("shiro")
}
/*
 * 方法说明: 统一请求封装
 * description: 
 * @param {url String 请求路径, params Object 请求参数, other Object 其他参数} 其他参数具体见httpConfig   
 * @return 
 * @createTime: 2021-6-2 14:37:42
 */
function request(url, params, other) {


	other = {
		...httpConfig,
		...other
	};
	// let cookie = cookies.set('Set-Cookie', 100, { domain: 'example.com' })
	// 防止莫名其妙token有时不刷新问题
	other.header['token'] = ''
	let data = {
		...params,
		// isSee:other.isSee
	}

	return new Promise((resolve, reject) => {

		// 是否显示loading
		// 加一个是否已有timer定时器的判断，否则有两个同时请求的时候，后者会清除前者的定时器id
		// 而没有清除前者的定时器，导致前者超时，一直显示loading
		if (other.showLoading && !other.timer) {
			httpConfig.timer = setTimeout(() => {
				uni.showLoading({
					title: other.loadingText,
					mask: other.loadingMask
				})
				other.timer = null;
			}, other.loadingTime);
		}


		uni.request({
			// url: (url.indexOf('https') > -1) ? url : (host + url),
			url: url,
			data: data,
			header: other.header,
			method: other.method || 'GET',
			timeout: other.timeout,
			responseType: url === '/api/v1/captcha' ? 'arraybuffer' : 'text',
			complete: async (data) => {
				let pages = getCurrentPages();
				// console.log('当前页面的路由：', pages, pages[pages.length - 1].$page.fullPath)
				console.log('url', data);
				// 请求返回后，隐藏loading(如果请求返回快的话，可能会没有loading)
				uni.hideLoading();
				// 清除定时器，如果请求回来了，就无需loading
				clearTimeout(httpConfig.timer);
				httpConfig.timer = null;
			
				
				if (data.statusCode == 200) {
					// 白名单直接通过
					if (requestWhiteList.includes(url)) {
						
						if (data) resolve(data);
					} else if (data.data && !expired) {
						expired = false;
						console.log('http1', url);
						
						if (data.data) resolve(data.data);
						else {
							if (httpConfig.errorOutput) {
								uni.showToast({
									title: data.data.msg || data.data.message || '请求失败',
									icon: 'none'
								})
								console.log('需要注释');
							}
							console.log('http2');
							reject(data.data);
						}
					} else {
						// console.log('获取新token');
						
						// 	// getCurrentPages() 函数用于获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
						// 	let pages = getCurrentPages();
						// 	// console.log('当前页面的路由：', pages[pages.length - 1].$page.fullPath)
						// 	if (pages[pages.length - 1].$page.fullPath == '/pages/login/app-login')
						// 		return
						// 	uni.reLaunch({
						// 		url: '/pages/login/app-login'
						// 	});
						// 	expired = true;
						// 	if (httpConfig.errorOutput) {
						// 		uni.showToast({
						// 			title: '身份已过期',
						// 			icon: 'none'
						// 		})
						// 	}
							// reject(data.data)

					}
				} else {
					
					console.warn(host + url, data);

					if (data.errMsg == 'request:fail ') {
						uni.showToast({
							title: '请求失败',
							icon: 'none'
						})
						// 需要注释
					}
					reject(data)
				}
				
			}
		});
	})
}

function getRequest(url, params, other) {
	return request(url, params, {
		...other,
		method: 'GET'
	})
}

function postRequest(url, params, other) {
	return request(url, params, {
		...other,
		method: 'POST'
	})
}

function getHost(url = '') {
	return host + url;
}

function getToken() {
	if (resqNum == 1) return
	uni.showLoading({
		title: '自动登录中'
	})
	console.log('获取token');
	uni.login({
		async success(e) {
			console.log(e.code);
			let url = '/api/v1/new_token'
			let params = {
				code: e.code
			}
			let res = await request(url, params, {
				method: 'GET'
			})
			console.log(res, '方法的res');
			if (res.code == 200) {
				uni.setStorageSync('token', res.data.token)
				// requestQueue.map(async (item) => {
				// 	await request(item.url, item.params, item.other)
				// })
				resqNum = 1
				uni.reLaunch({
					url: '/pages/index/index'
				})
				uni.hideLoading()
				uni.showToast({
					title: '登录成功',
					icon: 'none'
				})
				tokenLoading = false
				requestQueue = []
			} else {
				uni.removeStorageSync('token')
				let pages = getCurrentPages();
				if (pages[pages.length - 1].$page.fullPath == '/pages/login/app-login')
					return
				uni.reLaunch({
					url: '/pages/login/app-login'
				});
				uni.hideLoading()
				console.log('请手动登录');
				setTimeout(()=>{
					uni.showToast({
						title: '请手动登录',
						icon: 'none'
					})
				},1000)
				
				expired = true;
				if (httpConfig.errorOutput) {
					uni.showToast({
						title: '身份已过期',
						icon: 'none'
					})
				}
			}
		},
		fail() {
			console.log('自动登录失败,请手动登录');
			uni.showToast({
				title: '自动登录失败,请手动登录'
			})
		}
	})


}

function getFile(id, cache = true) {
	if (cache) {
		const uuid = `${host}${id}`
		let imgBase64 = uni.getStorageSync(uuid)
		if (imgBase64) {
			return imgBase64
		} else {
			setTimeout(async () => {
				imgBase64 = await uni.$pathToBase64(`${host}/sysFileInfo/preview?id=${id}`)
				uni.setStorageSync(uuid, imgBase64)
			}, 0)
			return `${host}/sysFileInfo/preview?id=${id}`
		}
	} else {
		return `${host}/sysFileInfo/preview?id=${id}`
	}

}
// ?key=your_api_key&location=shanghai&language=zh-Hans&days=5
function weatherRequest(url, params, other) {
	return request(url, {
		...params,
		key: weatherKey,
		language: 'zh-Hans',

	}, {
		...other,
		method: 'GET'
	})
}
function getRead(url, params, other) {
	
	return request(config.readUrl+url, params, {
		...other,
		method: 'GET'
	})
}
function postRead(url, params, other) {
	return request(config.readUrl+url, params, {
		...other,
		method: 'POST'
	})
}
export default {
	request,
	getRequest,
	postRequest,
	getHost,
	getFile,
	weatherRequest,
	getToken,
	getRead,postRead
}